// KFSpecMakeView.m
#import "KFSpecMakeView.h"
#import "SDAutoLayout.h"
#import "Mytools.h"

@interface KFSpecMakeView()

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *containerView; // 添加容器视图
@property (nonatomic, strong) UILabel *countLabel;
@property (nonatomic, assign) NSInteger quantity;

// 假数据
@property (nonatomic, strong) NSArray *specsArray;
@property (nonatomic, strong) NSArray *practicesArray;
@property(nonatomic, strong) KFProductModel *dataModel;
@property (nonatomic, strong) NSArray *beansArray; // 添加豆子数组
@property (nonatomic, strong) NSMutableArray *selectedBeans; // 添加选中的豆子
@property (nonatomic, strong) UILabel *totalPriceLabel;

// --- 新增属性 ---
// 为了让 scrollView 能在顶部和底部视图之间布局
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIView *bottomView;
// --- 新增属性结束 ---

@end

@implementation KFSpecMakeView

- (instancetype)initWithFrame:(CGRect)frame model:(KFProductModel*)model{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataModel = model;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        [self setupData];
        [self createUI];
        [self setupGestures];
    }
    return self;
}

- (void)setupData {
    self.quantity = self.dataModel.selectedSpecs.count>0?(self.dataModel.choseCount > 0 ? self.dataModel.choseCount : 1):1;
    self.selectedSpecs = [NSMutableArray arrayWithArray:self.dataModel.selectedSpecs ?: @[]];
    self.selectedPractices = [NSMutableArray arrayWithArray:self.dataModel.selectedPractices ?: @[]];
    self.selectedBeans = [NSMutableArray new];
    self.specsArray = self.dataModel.specList;
    NSMutableArray * arr = [NSMutableArray new];
    for (KFDishCookList *practiceDict in self.dataModel.cooksList)  {
        if (practiceDict.cooksData && ![practiceDict.cooksData isEqualToString:@"[]"]) {
            [arr addObject:practiceDict];
        }
    }
    self.practicesArray = arr;
    NSString *beanString = self.dataModel.bean; // "GEISHA_WASHED,KENYA_AA"
   if (beanString && beanString.length > 0) {
       self.beansArray = [beanString componentsSeparatedByString:@","];
       // 如果豆子数量为1，默认选中这个豆子
//       if (self.beansArray.count == 1) {
//           [self.selectedBeans addObject:self.beansArray.firstObject];
//       }
   } else {
       self.beansArray = @[];
   }
   
   // 默认选中第一个规格（如果没有已选规格）
   if (self.selectedSpecs.count == 0 && self.specsArray.count > 0) {
       [self.selectedSpecs addObject:self.specsArray.firstObject];
   }
   
   // 默认选中每个做法分区的第一个选项（如果没有已选做法）
   if (self.selectedPractices.count == 0 && self.practicesArray.count > 0) {
       for (KFDishCookList *practiceList in self.practicesArray) {
           NSArray *options = (NSArray*)[Mytools dictionaryWithJsonString:practiceList.cooksData];
           if (options && options.count > 0) {
               [self.selectedPractices addObject:options.firstObject];
           }
       }
   }
    if (self.selectedBeans.count == 0 && self.beansArray.count > 0) {
       [self.selectedBeans addObject:self.beansArray.firstObject];
   }
}


- (void)createUI {
    // 创建内容视图
    [self createContentView];
    
    // --- 顺序调整 ---
    // 1. 创建固定在顶部的商品信息 (添加到 self.contentView)
    [self createProductInfo];
    
    // 2. 创建固定在底部的按钮 (添加到 self.contentView)
    [self createConfirmButton];
    
    // 3. 创建在中间滚动的视图 (添加到 self.contentView, 位于顶部和底部视图之间)
    [self createScrollView];
    // --- 顺序调整结束 ---
    
    // 4. 将这些内容添加到 *scrollView* 的 *containerView* 中 (实现滚动)
    [self createQuantitySection];
    [self createBeanSection];
    [self createSpecSection];
    [self createPracticeSections];
    
    // 强制布局更新
    [self layoutIfNeeded];
}

- (void)createContentView {
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.cornerRadius = 12;
    self.contentView.layer.masksToBounds = YES;
    [self addSubview:self.contentView];
    
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    self.contentView.sd_layout
    .leftSpaceToView(self, 0)
    .rightSpaceToView(self, 0)
    .bottomSpaceToView(self, 0)
    .heightIs(screenHeight * 0.65);
}

- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.alwaysBounceVertical = YES;
    // --- 修改：添加到 contentView ---
    [self.contentView addSubview:self.scrollView];
    
    // --- 布局修改 ---
    // 顶部约束：在 closeButton 下方 16 像素
    // 底部约束：在 bottomView 上方 0 像素
    self.scrollView.sd_layout
    .leftSpaceToView(self.contentView, 0)
    .rightSpaceToView(self.contentView, 0)
    .topSpaceToView(self.closeButton, 16) // 依赖顶部的关闭按钮
    .bottomSpaceToView(self.bottomView, 0); // 依赖底部的按钮栏
    // --- 布局修改结束 ---
    
    // 创建容器视图 (这个不变，仍在 scrollView 中)
    self.containerView = [[UIView alloc] init];
    [self.scrollView addSubview:self.containerView];
    
    self.containerView.sd_layout
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0)
    .topSpaceToView(self.scrollView, 0);
    
    // 移除底部约束，让容器视图高度决定scrollView的contentSize
    // 不要设置bottom约束，也不要设置高度
}
- (void)createProductInfo {
    // 商品名称
    UILabel *productNameLabel = [[UILabel alloc] init];
    productNameLabel.text = self.dataModel.name;
    productNameLabel.font = [UIFont boldSystemFontOfSize:18];
    productNameLabel.textColor = [UIColor blackColor];
    productNameLabel.numberOfLines = 0; // 允许多行显示
    // --- 修改：添加到 contentView ---
    [self.contentView addSubview:productNameLabel];
    productNameLabel.sd_layout
    .leftSpaceToView(self.contentView, 16) // 修改：相对 contentView 布局
    .topSpaceToView(self.contentView, 16) // 修改：相对 contentView 布局
    .heightIs(20);
    [productNameLabel setSingleLineAutoResizeWithMaxWidth:300];
    
//    NSString * pr = [NSString stringWithFormat:@"￥%.0lf",self.dataModel.price];
//    UILabel  * pricelab = [UILabel labelWithTitle:pr color:UIColor.redColor fontSize:16];
//    // --- 修改：添加到 contentView ---
//    [self.contentView addSubview:pricelab];
//    pricelab.sd_layout.leftSpaceToView(productNameLabel, 10).centerYEqualToView(productNameLabel).heightIs(20);
//    [pricelab setSingleLineAutoResizeWithMaxWidth:300];
    self.totalPriceLabel = [[UILabel alloc] init];
    self.totalPriceLabel.text = @"￥0";
    self.totalPriceLabel.font = [UIFont boldSystemFontOfSize:18];
    self.totalPriceLabel.textColor = [UIColor systemRedColor];
    // --- 修改：添加到 self.bottomView ---
    [self.contentView addSubview:self.totalPriceLabel];
    self.totalPriceLabel.sd_layout.leftSpaceToView(productNameLabel, 10).centerYEqualToView(productNameLabel).heightIs(20);
    [self.totalPriceLabel setSingleLineAutoResizeWithMaxWidth:300];
    
    // 关闭按钮
    // --- 修改：使用属性 self.closeButton ---
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setTitle:@"✕" forState:UIControlStateNormal];
    [self.closeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.closeButton addTarget:self action:@selector(closeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    // --- 修改：添加到 contentView ---
    [self.contentView addSubview:self.closeButton];
    self.closeButton.sd_layout
    .rightSpaceToView(self.contentView, 16) // 修改：相对 contentView 布局
    .topSpaceToView(self.contentView, 16) // 修改：相对 contentView 布局
    .widthIs(30)
    .heightIs(30);
}
- (void)createBeanSection {
    // --- 注意：这里开始的视图都是添加到 self.containerView，这是正确的 ---
    UIView *lastView = self.containerView.subviews.lastObject;
    
    UIView *beanSection = [[UIView alloc] init];
    [self.containerView addSubview:beanSection];
    
    beanSection.sd_layout
    .leftSpaceToView(self.containerView, 0)
    .rightSpaceToView(self.containerView, 0)
    .topSpaceToView(lastView, 20);
    
    // 分区标题
    UILabel *beanTitleLabel = [[UILabel alloc] init];
    beanTitleLabel.text = @"选豆子";
    beanTitleLabel.font = [UIFont boldSystemFontOfSize:16];
    beanTitleLabel.textColor = [UIColor blackColor];
    [beanSection addSubview:beanTitleLabel];
    beanTitleLabel.sd_layout
    .leftSpaceToView(beanSection, 16)
    .topSpaceToView(beanSection, 0)
    .rightSpaceToView(beanSection, 16)
    .heightIs(20);
    
    // 豆子选项容器
    UIView *beanOptionsView = [[UIView alloc] init];
    [beanSection addSubview:beanOptionsView];
    beanOptionsView.sd_layout
    .leftSpaceToView(beanSection, 16)
    .rightSpaceToView(beanSection, 16)
    .topSpaceToView(beanTitleLabel, 12);
    
    // 获取单例中的豆子列表
    VicSingleObject *single = [VicSingleObject getInstance];
    NSArray *beansList = single.beansList;
    
    // 动态计算按钮布局
    CGFloat availableWidth = [UIScreen mainScreen].bounds.size.width - 32;
    CGFloat horizontalSpacing = 12;
    CGFloat verticalSpacing = 10;
    CGFloat buttonHeight = 32;
    
    CGFloat currentX = 0;
    CGFloat currentY = 0;
    CGFloat currentLineHeight = 0;
    
    for (int i = 0; i < self.beansArray.count; i++) {
        NSString *beanValue = self.beansArray[i];
        NSString *beanName = beanValue; // 默认显示英文值
        
        // 在beansList中查找对应的中文名称
        for (NSDictionary *beanDict in beansList) {
            NSString *value = beanDict[@"beanValue"];
            if ([value isEqualToString:beanValue]) {
                beanName = beanDict[@"beanName"]; // 找到对应的中文名
                break;
            }
        }
        
        // 计算按钮宽度
        CGFloat textWidth = [beanName boundingRectWithSize:CGSizeMake(MAXFLOAT, buttonHeight)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}
                                               context:nil].size.width;
        
        CGFloat buttonWidth = textWidth + 20;
        
        // 检查是否需要换行
        if (currentX + buttonWidth > availableWidth && currentX > 0) {
            currentX = 0;
            currentY += buttonHeight + verticalSpacing;
        }
        
        UIButton *beanButton = [self createBeanOptionButtonWithTitle:beanName tag:3000 + i];
        [beanOptionsView addSubview:beanButton];
        
        // 默认选中第一个
//        if (i == 0) {
//            beanButton.selected = YES;
//            beanButton.backgroundColor = [UIColor systemBlueColor];
//            beanButton.layer.borderColor = [UIColor systemBlueColor].CGColor;
//            [self.selectedBeans addObject:beanValue]; // 保存英文值
//        }
        if ([self.selectedBeans containsObject:beanValue]) {
            beanButton.selected = YES;
            beanButton.backgroundColor = [UIColor systemBlueColor];
            beanButton.layer.borderColor = [UIColor systemBlueColor].CGColor;
        }
        
        [beanButton addTarget:self action:@selector(beanButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        beanButton.sd_layout
        .leftSpaceToView(beanOptionsView, currentX)
        .topSpaceToView(beanOptionsView, currentY)
        .widthIs(buttonWidth)
        .heightIs(buttonHeight);
        
        currentX += buttonWidth + horizontalSpacing;
        currentLineHeight = buttonHeight;
    }
    
    // 计算beanOptionsView的高度
    CGFloat beanOptionsViewHeight = currentY + currentLineHeight;
    beanOptionsView.sd_layout.heightIs(beanOptionsViewHeight);
    [beanSection setupAutoHeightWithBottomView:beanOptionsView bottomMargin:16];
}
- (UIButton *)createBeanOptionButtonWithTitle:(NSString *)title tag:(NSInteger)tag {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    button.layer.borderColor = [UIColor lightGrayColor].CGColor;
    button.layer.borderWidth = 1;
    button.layer.cornerRadius = 4;
    button.tag = tag;
    return button;
}
- (void)beanButtonClicked:(UIButton *)sender {
    // 先将所有豆子按钮设为未选中状态
    for (UIView *subview in sender.superview.subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subview;
            button.selected = NO;
            button.backgroundColor = [UIColor whiteColor];
            button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        }
    }
    
    // 选中当前点击的按钮
    sender.selected = YES;
    sender.backgroundColor = [UIColor systemBlueColor];
    sender.layer.borderColor = [UIColor systemBlueColor].CGColor;
    
    // 更新选中的豆子（单选，只保留一个）
    NSInteger index = sender.tag - 3000;
    NSString *beanValue = self.beansArray[index];
    [self.selectedBeans removeAllObjects];
    [self.selectedBeans addObject:beanValue];
    // 如果豆子有价格差异，这里也需要更新总价
        // [self updateTotalPrice];
}
- (void)createPracticeSections {
    // --- 注意：添加到 self.containerView ---
    UIView *lastView = self.containerView.subviews.lastObject;
    UIView *currentLastView = lastView;
    NSInteger sectionIndex = 0;
    for (KFDishCookList *practiceDict in self.practicesArray) {
        if (practiceDict.cooksData && ![practiceDict.cooksData isEqualToString:@"[]"]) {
            UIView *practiceSection = [[UIView alloc] init];
            [self.containerView addSubview:practiceSection];
            
            practiceSection.sd_layout
            .leftSpaceToView(self.containerView, 0)
            .rightSpaceToView(self.containerView, 0)
            .topSpaceToView(currentLastView, 20);
            
            // 分区标题
            UILabel *practiceTitleLabel = [[UILabel alloc] init];
            practiceTitleLabel.text = practiceDict.cooksTitle;
            practiceTitleLabel.font = [UIFont boldSystemFontOfSize:16];
            practiceTitleLabel.textColor = [UIColor blackColor];
            [practiceSection addSubview:practiceTitleLabel];
            practiceTitleLabel.sd_layout
            .leftSpaceToView(practiceSection, 16)
            .topSpaceToView(practiceSection, 0)
            .rightSpaceToView(practiceSection, 16)
            .heightIs(20);
            
            // 做法选项容器
            UIView *practiceOptionsView = [[UIView alloc] init];
            [practiceSection addSubview:practiceOptionsView];
            practiceOptionsView.sd_layout
            .leftSpaceToView(practiceSection, 16)
            .rightSpaceToView(practiceSection, 16)
            .topSpaceToView(practiceTitleLabel, 12);
            
            // 创建做法按钮 - 使用动态布局
            NSArray *options = (NSArray*)[Mytools dictionaryWithJsonString:practiceDict.cooksData];
            
            // 动态计算按钮布局
            CGFloat availableWidth = [UIScreen mainScreen].bounds.size.width - 32; // 左右各16边距
            CGFloat horizontalSpacing = 12;
            CGFloat verticalSpacing = 10;
            CGFloat buttonHeight = 32;
            
            CGFloat currentX = 0;
            CGFloat currentY = 0;
            CGFloat currentLineHeight = 0;
            
            for (int i = 0; i < options.count; i++) {
                NSDictionary *dic = options[i];
                NSString * title = dic[@"cookName"];
                NSString *priceStr = dic[@"cookPrice"];
                NSString *buttonTitle = @"";
                if (priceStr && priceStr.length>0) {
                    if ([priceStr doubleValue] > 0) {
                        buttonTitle = [NSString stringWithFormat:@"%@ ➕￥%@", title, priceStr];
                    }else{
                        buttonTitle = [NSString stringWithFormat:@"%@ ➖￥%@", title, [priceStr stringByReplacingOccurrencesOfString:@"-" withString:@""]];
                    }
                }else{
                    buttonTitle = [NSString stringWithFormat:@"%@", title];
                }
                    
                // 计算按钮需要的宽度（根据文本长度）
                CGFloat textWidth = [buttonTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, buttonHeight)
                                                           options:NSStringDrawingUsesLineFragmentOrigin
                                                        attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}
                                                           context:nil].size.width;
                    
                // 完全自适应宽度
                CGFloat buttonWidth = textWidth + 20; // 左右各10边距
                
                // 检查是否需要换行
                if (currentX + buttonWidth > availableWidth && currentX > 0) {
                    currentX = 0;
                    currentY += buttonHeight + verticalSpacing;
                }
                NSInteger buttonTag = 2000 + (sectionIndex * 100) + i;
                UIButton *practiceButton = [self createOptionButtonWithTitle:buttonTitle tag:buttonTag];
                [practiceOptionsView addSubview:practiceButton];
                
                // 回显：检查当前做法是否在已选数组中
                for (NSDictionary *selectedPractice in self.selectedPractices) {
                    if ([selectedPractice[@"cookName"] isEqualToString:title]) {
                        practiceButton.selected = YES;
                        practiceButton.backgroundColor = [UIColor systemBlueColor];
                        practiceButton.layer.borderColor = [UIColor systemBlueColor].CGColor;
                        break;
                    }
                }
                [practiceButton addTarget:self action:@selector(practiceButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
                
                practiceButton.sd_layout
                .leftSpaceToView(practiceOptionsView, currentX)
                .topSpaceToView(practiceOptionsView, currentY)
                .widthIs(buttonWidth)
                .heightIs(buttonHeight);
                
                currentX += buttonWidth + horizontalSpacing;
                currentLineHeight = buttonHeight;
            }
            
            // 计算practiceOptionsView的高度
            CGFloat practiceOptionsViewHeight = currentY + currentLineHeight;
            practiceOptionsView.sd_layout.heightIs(practiceOptionsViewHeight);
            [practiceSection setupAutoHeightWithBottomView:practiceOptionsView bottomMargin:16];
            
            currentLastView = practiceSection;
            sectionIndex++;
        }
        
    }
    
    // 设置容器视图的底部约束 - 这是关键，确保scrollView知道内容高度
    [self.containerView setupAutoHeightWithBottomView:currentLastView bottomMargin:20];
        
    // 重要：手动设置scrollView的内容大小
    [self.scrollView setupAutoContentSizeWithBottomView:self.containerView bottomMargin:0];
}

// 在showInView方法中添加，确保布局完全更新
- (void)showInView:(UIView *)view {
    [view addSubview:self];
    
    // 初始位置在屏幕下方
    self.contentView.transform = CGAffineTransformMakeTranslation(0, self.contentView.frame.size.height);
    
    // 确保布局完全更新
    [self layoutIfNeeded];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.transform = CGAffineTransformIdentity;
    }];
}

- (void)createQuantitySection {
    // --- 注意：添加到 self.containerView ---
    UIView *lastView = self.containerView.subviews.lastObject;
    
    UIView *quantityView = [[UIView alloc] init];
    [self.containerView addSubview:quantityView];
    
    // --- 重点：lastView 逻辑 ---
    // 因为 createProductInfo 不再向 containerView 添加
    // 所以这里的 lastView 第一次会是 nil
    if (lastView) {
        //  subsequent sections (bean, spec, practice) will take this path
        quantityView.sd_layout
        .leftSpaceToView(self.containerView, 0)
        .rightSpaceToView(self.containerView, 0)
        .topSpaceToView(lastView, 20)
        .heightIs(50);
    } else {
        // This is the FIRST section in containerView, will take this path
        quantityView.sd_layout
        .leftSpaceToView(self.containerView, 0)
        .rightSpaceToView(self.containerView, 0)
        .topSpaceToView(self.containerView, 20) // 修改：顶部改为相对 containerView
        .heightIs(50);
    }
    // --- 重点结束 ---
    
    UILabel *quantityLabel = [[UILabel alloc] init];
    quantityLabel.text = @"数量";
    quantityLabel.font = [UIFont systemFontOfSize:16];
    quantityLabel.textColor = [UIColor blackColor];
    [quantityView addSubview:quantityLabel];
    quantityLabel.sd_layout
    .leftSpaceToView(quantityView, 16)
    .centerYEqualToView(quantityView)
    .widthIs(60)
    .heightIs(20);
    
    // 减按钮
    UIButton *minusButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [minusButton setTitle:@"-" forState:UIControlStateNormal];
    [minusButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    minusButton.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    minusButton.layer.cornerRadius = 4;
    [minusButton addTarget:self action:@selector(decreaseQuantity) forControlEvents:UIControlEventTouchUpInside];
    [quantityView addSubview:minusButton];
    minusButton.sd_layout
    .rightSpaceToView(quantityView, 116)
    .centerYEqualToView(quantityView)
    .widthIs(30)
    .heightIs(30);
    
    // 数量显示
    self.countLabel = [[UILabel alloc] init];
    self.countLabel.text = [NSString stringWithFormat:@"%ld", (long)self.quantity];
    self.countLabel.textAlignment = NSTextAlignmentCenter;
    self.countLabel.font = [UIFont systemFontOfSize:16];
    self.countLabel.textColor = [UIColor blackColor];
    [quantityView addSubview:self.countLabel];
    self.countLabel.sd_layout
    .leftSpaceToView(minusButton, 8)
    .centerYEqualToView(quantityView)
    .widthIs(40)
    .heightIs(30);
    
    // 加按钮
    UIButton *plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [plusButton setTitle:@"+" forState:UIControlStateNormal];
    [plusButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    plusButton.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    plusButton.layer.cornerRadius = 4;
    [plusButton addTarget:self action:@selector(increaseQuantity) forControlEvents:UIControlEventTouchUpInside];
    [quantityView addSubview:plusButton];
    plusButton.sd_layout
    .leftSpaceToView(self.countLabel, 8)
    .centerYEqualToView(quantityView)
    .widthIs(30)
    .heightIs(30);
}

- (void)createSpecSection {
    // --- 注意：添加到 self.containerView ---
    UIView *lastView = self.containerView.subviews.lastObject;
    
    UIView *specSection = [[UIView alloc] init];
    [self.containerView addSubview:specSection];
    
    specSection.sd_layout
    .leftSpaceToView(self.containerView, 0)
    .rightSpaceToView(self.containerView, 0)
    .topSpaceToView(lastView, 20);
    
    UILabel *specTitleLabel = [[UILabel alloc] init];
    specTitleLabel.text = @"规格";
    specTitleLabel.font = [UIFont boldSystemFontOfSize:16];
    specTitleLabel.textColor = [UIColor blackColor];
    [specSection addSubview:specTitleLabel];
    specTitleLabel.sd_layout
    .leftSpaceToView(specSection, 16)
    .topSpaceToView(specSection, 0)
    .rightSpaceToView(specSection, 16)
    .heightIs(20);
    
    // 规格按钮容器
    UIView *specButtonsView = [[UIView alloc] init];
    [specSection addSubview:specButtonsView];
    specButtonsView.sd_layout
    .leftSpaceToView(specSection, 16)
    .rightSpaceToView(specSection, 16)
    .topSpaceToView(specTitleLabel, 12);
    
    // 动态计算按钮布局
    CGFloat availableWidth = [UIScreen mainScreen].bounds.size.width - 32; // 左右各16边距
    CGFloat horizontalSpacing = 12;
    CGFloat verticalSpacing = 10;
    CGFloat buttonHeight = 32;
    CGFloat minButtonWidth = 60;
    CGFloat maxButtonWidth = 100;
    
    CGFloat currentX = 0;
    CGFloat currentY = 0;
    CGFloat currentLineHeight = 0;
    
    for (int i = 0; i < self.specsArray.count; i++) {
        KFDishSpecList *spec = self.specsArray[i];
        NSString *title = spec.specName;
        NSString *buttonTitle = @"";
        if (spec.specPrice) {
            if ((double)spec.specPrice > 0) {
                buttonTitle = [NSString stringWithFormat:@"%@ ➕￥%.0lf", title, (double)spec.specPrice];
            }else{
                buttonTitle = [NSString stringWithFormat:@"%@ ➖￥%.0lf", title, fabs((double)spec.specPrice)];
            }
        }else{
            buttonTitle = [NSString stringWithFormat:@"%@", title];
        }
            // 计算按钮需要的宽度（根据文本长度）
            CGFloat textWidth = [buttonTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, buttonHeight)
                                                       options:NSStringDrawingUsesLineFragmentOrigin
                                                    attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}
                                                       context:nil].size.width;
            
            // 完全自适应宽度，不要限制最大宽度
            CGFloat buttonWidth = textWidth + 20; // 左右各10边距
        
        // 检查是否需要换行
        if (currentX + buttonWidth > availableWidth && currentX > 0) {
            currentX = 0;
            currentY += buttonHeight + verticalSpacing;
        }
        
        UIButton *specButton = [self createOptionButtonWithTitle:buttonTitle tag:1000 + i];
        [specButtonsView addSubview:specButton];
        
        if ([self.selectedSpecs containsObject:spec]) {
            specButton.selected = YES;
            specButton.backgroundColor = [UIColor systemBlueColor];
            specButton.layer.borderColor = [UIColor systemBlueColor].CGColor;
        }
        [specButton addTarget:self action:@selector(specButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        specButton.sd_layout
        .leftSpaceToView(specButtonsView, currentX)
        .topSpaceToView(specButtonsView, currentY)
        .widthIs(buttonWidth)
        .heightIs(buttonHeight);
        
        currentX += buttonWidth + horizontalSpacing;
        currentLineHeight = buttonHeight;
    }
    
    // 计算specButtonsView的高度
    CGFloat specButtonsViewHeight = currentY + currentLineHeight;
    specButtonsView.sd_layout.heightIs(specButtonsViewHeight);
    [specSection setupAutoHeightWithBottomView:specButtonsView bottomMargin:16];
}
- (void)createConfirmButton {
    // --- 修改：使用属性 self.bottomView ---
    // 创建容器视图
    self.bottomView = [[UIView alloc] init];
    [self.contentView addSubview:self.bottomView];
    
    self.bottomView.sd_layout
    .leftSpaceToView(self.contentView, 0)
    .rightSpaceToView(self.contentView, 0)
    .bottomSpaceToView(self.contentView, 0)
    .heightIs(60);
    
    // 总价标签
//    self.totalPriceLabel = [[UILabel alloc] init];
//    self.totalPriceLabel.text = @"￥0";
//    self.totalPriceLabel.font = [UIFont boldSystemFontOfSize:18];
//    self.totalPriceLabel.textColor = [UIColor systemRedColor];
//    // --- 修改：添加到 self.bottomView ---
//    [self.bottomView addSubview:self.totalPriceLabel];
//    
//    self.totalPriceLabel.sd_layout
//    .leftSpaceToView(self.bottomView, 16)
//    .centerYEqualToView(self.bottomView)
//    .heightIs(25);
    [self.totalPriceLabel setSingleLineAutoResizeWithMaxWidth:200];
    
    // 确定按钮
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmButton.backgroundColor = [UIColor systemBlueColor];
    confirmButton.layer.cornerRadius = 8;
    [confirmButton addTarget:self action:@selector(confirmButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    // --- 修改：添加到 self.bottomView ---
    [self.bottomView addSubview:confirmButton];
    
    confirmButton.sd_layout
    .rightSpaceToView(self.bottomView, 16)
    .centerYEqualToView(self.bottomView)
    .leftSpaceToView(self.bottomView, 16)
    .heightIs(44);
    
    // 初始化计算总价
    [self updateTotalPrice];
}
- (void)updateTotalPrice {
    CGFloat totalPrice = 0;
    
    // 获取商品基础价格
    CGFloat basePrice = self.dataModel.price;
    totalPrice += basePrice;
    
    // 加上规格价格
    if (self.selectedSpecs.count > 0) {
        KFDishSpecList *spec = self.selectedSpecs.firstObject;
        totalPrice += spec.specPrice;
    }
    
    // 加上做法价格
    for (NSDictionary *practice in self.selectedPractices) {
        CGFloat practicePrice = [practice[@"cookPrice"] floatValue];
        totalPrice += practicePrice;
    }
    
    // 乘以数量
    totalPrice *= self.quantity;
    
    // 更新总价显示
    self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.0lf", totalPrice];
}
- (UIButton *)createOptionButtonWithTitle:(NSString *)title tag:(NSInteger)tag {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // *** 核心修改：直接设置标题 ***
    // 无论是规格还是做法，传入的 title 已经是我们计算好的最终显示内容了
    [button setTitle:title forState:UIControlStateNormal];

    /* 删掉你原来方法里关于 tag >= 1000, tag >= 2000 的所有 if/else if 判断逻辑，
     它们是多余的，并且 tag >= 2000 的分支是导致布局崩溃的根源。
    */
    
    button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10); // 左右内边距
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    button.layer.borderColor = [UIColor lightGrayColor].CGColor;
    button.layer.borderWidth = 1;
    button.layer.cornerRadius = 4;
    button.tag = tag;
    return button;
}

- (void)setupGestures {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:tap];
}

#pragma mark - 按钮事件
- (void)closeButtonClicked {
    [self dismiss];
    if (self.closeBlock) {
        self.closeBlock();
    }
}

- (void)confirmButtonClicked {
    [self dismiss];
    if (self.confirmBlock) {
        // 收集做法标题 (这部分逻辑保持不变)
        NSMutableArray *practiceTitles = [NSMutableArray array];
        for (KFDishCookList *practiceList in self.practicesArray) {
            [practiceTitles addObject:practiceList.cooksTitle ?: @""];
        }
        
        // --- 排序逻辑：按照 self.practicesArray (后端返回的顺序) 来排序已选做法 ---
        NSMutableArray *sortedSelectedPractices = [NSMutableArray array];
        
        // 1. 遍历后端定义的做法分区 (self.practicesArray 已经在 setupData 中被过滤，只包含有选项的分区)
        for (KFDishCookList *practiceList in self.practicesArray) {
            
            // 2. 获取当前分区的 *所有* 做法选项
            NSArray *options = (NSArray*)[Mytools dictionaryWithJsonString:practiceList.cooksData];
            
            // 3. 检查 self.selectedPractices (用户当前选择的) 中，是否有任何一项
            //    存在于当前分区的选项(options)中
            for (NSDictionary *selectedPractice in self.selectedPractices) {
                if ([options containsObject:selectedPractice]) {
                    
                    // 4. 如果找到了，说明用户选了这一分区的做法，将其加入到
                    //    sortedSelectedPractices 数组中
                    [sortedSelectedPractices addObject:selectedPractice];
                    
                    // 5. 因为每个分区都是单选，找到一个后就可以跳出内层循环，
                    //    继续检查下一个分区
                    break;
                }
            }
        }
        // --- 排序逻辑结束 ---
        
        // 使用排序后的数组 'sortedSelectedPractices' 替换原来的 '[self.selectedPractices copy]'
        self.confirmBlock(self.quantity, [self.selectedSpecs copy], [sortedSelectedPractices copy], [self.selectedBeans copy], [practiceTitles copy]);
    }
}

- (void)decreaseQuantity {
    if (self.quantity > 1) {
        self.quantity--;
        self.countLabel.text = [NSString stringWithFormat:@"%ld", (long)self.quantity];
        [self updateTotalPrice];
    }
}

- (void)increaseQuantity {
    self.quantity++;
    self.countLabel.text = [NSString stringWithFormat:@"%ld", (long)self.quantity];
    [self updateTotalPrice];
}
- (void)specButtonClicked:(UIButton *)sender {
    // 先将所有规格按钮设为未选中状态
    for (UIView *subview in sender.superview.subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subview;
            button.selected = NO;
            button.backgroundColor = [UIColor whiteColor];
            button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        }
    }
    
    // 选中当前点击的按钮
    sender.selected = YES;
    sender.backgroundColor = [UIColor systemBlueColor];
    sender.layer.borderColor = [UIColor systemBlueColor].CGColor;
    
    // 更新选中的规格（单选，只保留一个）
    NSInteger index = sender.tag - 1000;
    KFDishSpecList *spec = self.specsArray[index];
    [self.selectedSpecs removeAllObjects];
    [self.selectedSpecs addObject:spec];
    [self updateTotalPrice];
}

- (void)practiceButtonClicked:(UIButton *)sender {
    // *** 核心修改：解码Tag ***
    NSInteger tag = sender.tag;
    
    // 基础Tag是2000
    NSInteger rawIndex = tag - 2000;
    
    // 计算分区索引 (例如：2105 -> rawIndex=105 -> sectionIndex = 1)
    NSInteger sectionIndex = rawIndex / 100;
    
    // 计算分区内的按钮索引 (例如：2105 -> rawIndex=105 -> itemIndex = 5)
    NSInteger itemIndex = rawIndex % 100;
    
    // --- 安全检查 ---
    if (sectionIndex >= self.practicesArray.count) {
        NSLog(@"错误：做法分区索引越界");
        return;
    }
    
    // --- 直接获取数据 ---
    KFDishCookList *practiceList = self.practicesArray[sectionIndex];
    NSArray *options = (NSArray*)[Mytools dictionaryWithJsonString:practiceList.cooksData];
    
    // --- 再次安全检查 ---
    if (itemIndex >= options.count) {
        NSLog(@"错误：做法选项索引越界");
        return;
    }
    
    NSDictionary *targetPracticeDict = options[itemIndex];
    
    // --- 界面更新：将同一分区的所有做法按钮设为未选中状态 ---
    UIView *practiceOptionsView = sender.superview;
    for (UIView *subview in practiceOptionsView.subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subview;
            button.selected = NO;
            button.backgroundColor = [UIColor whiteColor];
            button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        }
    }
    
    // 选中当前点击的按钮
    sender.selected = YES;
    sender.backgroundColor = [UIColor systemBlueColor];
    sender.layer.borderColor = [UIColor systemBlueColor].CGColor;
    
    
    // --- START: 修正后的数据更新逻辑 ---
    // 目标：实现“分区内单选”
    
    // 1. 找出这个分区 *所有* 可能的选项
    // (在上面已经获取了: 'options')
    
    // 2. 移除 self.selectedPractices 中所有 *属于这个分区* 的旧选项
    // (我们通过检查 'options' 数组是否包含已选项来判断它是否属于这个分区)
    NSMutableArray *practicesToRemove = [NSMutableArray array];
    for (NSDictionary *selectedPractice in self.selectedPractices) {
        if ([options containsObject:selectedPractice]) {
            [practicesToRemove addObject:selectedPractice];
        }
    }
    [self.selectedPractices removeObjectsInArray:practicesToRemove];
    
    // 3. 添加当前点击的新选项
    [self.selectedPractices addObject:targetPracticeDict];
    [self updateTotalPrice];
}


- (void)handleTap:(UITapGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:self];
    if (!CGRectContainsPoint(self.contentView.frame, point)) {
        [self dismiss];
    }
}



- (void)dismiss {
    [UIView animateWithDuration:0.3 animations:^{
           self.contentView.transform = CGAffineTransformMakeTranslation(0, self.contentView.frame.size.height);
           self.alpha = 0;
       } completion:^(BOOL finished) {
           [self removeFromSuperview];
       }];
}

@end
